// 全局变量
let forecastChart = null;
let componentsChart = null;
let rangeSlider = null;
let allTimestamps = [];
let allChartData = {};
let currentStart = 0;
let currentEnd = 0;

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOMContentLoaded 事件已触发');
    initCharts();
    bindEvents();
});

function initCharts() {
    try {
        // 安全销毁现有图表
        [forecastChart, componentsChart].forEach(chart => {
            if (chart && !chart.isDisposed()) {
                chart.dispose();
            }
        });

        // 初始化新图表实例
        forecastChart = echarts.init(document.getElementById('forecast-chart'));
        componentsChart = echarts.init(document.getElementById('components-chart'));

        // 基础配置（必须包含完整的轴配置）
        const baseOption = {
            animation: false,
            tooltip: {
                trigger: 'axis',
                axisPointer: {type: 'cross'}
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisLabel: {
                    rotate: 30,
                    formatter: value => value.split(' ')[0] // 默认日期格式化
                }
            },
            yAxis: {
                type: 'value',
                name: '数值',
                axisLabel: {
                    formatter: value => value.toFixed(2)
                }
            }
        };

        // 应用基础配置（深拷贝避免污染）
        forecastChart.setOption(JSON.parse(JSON.stringify(baseOption)));
        componentsChart.setOption(JSON.parse(JSON.stringify(baseOption)));

        // 窗口大小自适应
        window.addEventListener('resize', () => {
            forecastChart?.resize();
            componentsChart?.resize();
        });

        setTimeout(() => bindEvents(), 100);
        document.querySelectorAll('.chart-box').forEach(box => {
            box.style.position = 'relative';  // 重要！
            box.style.overflow = 'visible';   // 确保手柄可见
        });
    } catch (e) {
        console.error('initCharts 函数出错:', e);
    }
}

function updateCharts(startIdx, endIdx) {
    console.log('updateCharts 函数被调用，参数：', startIdx, endIdx);
    try {
        // 强制类型转换和索引修正
        startIdx = Math.floor(Math.max(0, Number(startIdx)));
        endIdx = Math.ceil(Math.min(allTimestamps.length - 1, Number(endIdx)));
        // 安全验证
        if (startIdx > endIdx) [startIdx, endIdx] = [endIdx, startIdx];
        if (endIdx - startIdx < 1) {
            console.warn('时间范围过小，最少选择2个数据点');
            return;
        }

        const validTimestamps = allTimestamps.slice(startIdx, endIdx + 1);
        const dataSegments = {
            forecast: {
                xData: validTimestamps,
                series: [
                    getSeriesData('实际值', allChartData.originData, startIdx, endIdx),
                    getSeriesData('预测值', allChartData.predictData, startIdx, endIdx)
                ]
            },
            components: {
                xData: validTimestamps,
                series: [
                    getSeriesData('季节性', allChartData.seasonalData, startIdx, endIdx),
                    getSeriesData('趋势', allChartData.trendData, startIdx, endIdx),
                    getSeriesData('残差', allChartData.residualData, startIdx, endIdx)
                ]
            }
        };

        // 更新预测图表
        forecastChart.setOption({
            xAxis: { data: dataSegments.forecast.xData },
            series: dataSegments.forecast.series
        }, {
            replaceMerge: ['xAxis', 'series'],
            notMerge: false
        });

        // 更新组件图表
        componentsChart.setOption({
            xAxis: { data: dataSegments.components.xData },
            series: dataSegments.components.series
        }, {
            replaceMerge: ['xAxis', 'series'],
            notMerge: false
        });

        // 强制重绘
        forecastChart.resize();
        componentsChart.resize();
    } catch (error) {
        console.error('图表更新失败:', error);
        handleError(`图表渲染失败: ${error.message}`);
        throw error;
    }
}

// 辅助函数：创建标准化系列配置

// 辅助函数：获取安全的数据切片
function getSeriesData(name, dataArray, start, end) {
    const validData = (dataArray || [])
        .slice(start, end + 1)
        .map(v => Number(v) || 0);  // 确保数值类型

    return {
        name,
        type: 'line',
        data: validData,
        showSymbol: validData.length <= 100, // 大数据量时隐藏标记
        itemStyle: { color: getColorForSeries(name) },
        lineStyle: { width: 1.2 },
        smooth: true
    };
}

// 颜色映射
function getColorForSeries(name) {
    const colors = {
        '实际值': '#1890ff',
        '预测值': '#fca311',
        '季节性': '#28a745',
        '趋势': '#dc3545',
        '残差': '#6f42c1'
    };
    return colors[name] || '#666';
}

/*
function createSeries(name, dataArray, color, startIdx, endIdx) {
    return {
        name,
        type: 'line',
        data: (dataArray || []).slice(startIdx, endIdx + 1),
        symbol: 'none',
        itemStyle: { color },
        lineStyle: { width: 1.2 },
        emphasis: { lineStyle: { width: 2 } },
        smooth: true,
        progressive: 200, // 大数据量优化
        animation: false
    };
}
*/

// 数据验证函数（增强版）
function validateChartData(data) {
    try {
        const requiredFields = ['timestamps', 'originData', 'predictData'];
        const optionalFields = ['seasonalData', 'trendData', 'residualData'];

        // 1. 验证字段存在性
        requiredFields.forEach(field => {
            if (!data?.[field] || !Array.isArray(data[field])) {
                throw new Error(`缺少必要字段: ${field}`);
            }
        });

        // 2. 验证数据长度一致性
        const baseLength = data.timestamps.length;
        requiredFields.forEach(field => {
            if (data[field].length !== baseLength) {
                throw new Error(`${field} 数据长度不一致`);
            }
        });

        // 3. 验证可选字段
        optionalFields.forEach(field => {
            if (data[field] && !Array.isArray(data[field])) {
                throw new Error(`无效的 ${field} 格式`);
            }
        });

        return true;
    } catch (error) {
        console.error('数据验证失败:', error);
        return false;
    }
}

function validateIndexRange(start, end) {
    return start >= 0 &&
        end < allTimestamps.length &&
        start <= end &&
        allTimestamps.length > 0;
}

function bindEvents() {
    try {
        // 预测按钮点击事件
        const predictBtn = document.getElementById('predict-btn');
        if (!predictBtn) {
            console.error('未找到预测按钮元素');
            return;
        }
        predictBtn.addEventListener('click', getForecast);
        console.log('预测按钮事件绑定成功');

        // 范围控制按钮
        // document.getElementById('apply-range').addEventListener('click', applyDateRange);
        const applyRangeBtn = document.getElementById('apply-range');
        if (!applyRangeBtn) {
            console.error('未找到范围控制按钮元素');
            return;
        }
        applyRangeBtn.addEventListener('click', applyDateRange);

        // document.getElementById('reset-range').addEventListener('click', resetChartRange);
        const resetRangeBtn = document.getElementById('reset-range');
        if (!resetRangeBtn) {
            console.error('未找到重置按钮元素');
            return;
        }
        resetRangeBtn.addEventListener('click', resetChartRange);
        // 绑定调整手柄事件（增加存在性检查）
        console.log("绑定调整手柄前");
        setTimeout(() => {
            function bindResizeHandles() {
                const handles = document.querySelectorAll('.chart-resize-handle');
                console.log('找到调整手柄数量:', handles.length);

                handles.forEach(handle => {
                    handle.removeEventListener('mousedown', startResize);
                    handle.addEventListener('mousedown', startResize);
                });
            }

            // 初始化绑定
            bindResizeHandles();

            // 添加MutationObserver监听动态元素
            const observer = new MutationObserver((mutations) => {
                mutations.forEach(() => bindResizeHandles());
            });

            document.querySelectorAll('.chart-box').forEach(box => {
                observer.observe(box, { childList: true, subtree: true });
            });
        }, 500);
    } catch (e) {
        console.error('bindEvents 函数出错:', e);
    }
}

// 拖拽状态跟踪
let isResizing = false;
let currentChart = null;
let startX = 0;
let startY = 0;
let startWidth = 0;
let startHeight = 0;

function startResize(e) {
    e.preventDefault();
    console.debug('开始调整大小');

    isResizing = true;
    currentChart = e.target.closest('.chart-box');

    // 添加激活状态样式
    currentChart.classList.add('resizing');

    const rect = currentChart.getBoundingClientRect();
    startX = e.clientX;
    startY = e.clientY;
    startWidth = rect.width;
    startHeight = rect.height;

    document.addEventListener('mousemove', handleResize);
    document.addEventListener('mouseup', stopResize);
}

function handleResize(e) {
    if (!isResizing) return;

    const deltaX = e.clientX - startX;
    const deltaY = e.clientY - startY;

    const newWidth = Math.max(300, startWidth + deltaX);
    const newHeight = Math.max(200, startHeight + deltaY);

    currentChart.style.width = `${newWidth}px`;
    currentChart.style.height = `${newHeight}px`;

    // 同步更新图表
    forecastChart?.resize();
    componentsChart?.resize();
}

function stopResize() {
    console.debug('结束调整大小');
    isResizing = false;
    currentChart?.classList.remove('resizing');

    // 强制最终重绘
    forecastChart?.resize();
    componentsChart?.resize();

    document.removeEventListener('mousemove', handleResize);
    document.removeEventListener('mouseup', stopResize);
}

function getForecast() {
    const fileInput = document.getElementById('csv-file');
    const startHour = parseInt(document.getElementById('start-hour').value);
    const endHour = parseInt(document.getElementById('end-hour').value);
    const file = fileInput.files[0];
    // 重置状态
    resetUIState();

    if (!file) {
        showError('请选择一个CSV文件');
        return;
    }

    var cnt = 0;
    console.log(++cnt);
    if (isNaN(startHour) || isNaN(endHour)) {
        handleError('起始时间和终止时间必须是数字');
        return;
    }

    console.log(++cnt);

    if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23) {
        handleError('起始时间和终止时间必须在0到23之间');
        return;
    }

    console.log(++cnt);
    if (startHour > endHour) {
        handleError('起始时间必须小于或等于终止时间');
        return;
    }

    console.log("++cnt");
    console.log('getForecast() 函数参数:', file, startHour, endHour);
    // 显示加载状态
    showLoading();

    const formData = new FormData();
    formData.append('csvFile', file);
    const jsonData = {
        startHour: startHour,
        endHour: endHour
    };
    formData.append('timeRangeParam', JSON.stringify(jsonData));


    // 设置超时
    const timeout = setTimeout(() => {
        handleError('请求超时，请稍后再试');
    }, 300000);

    console.log("call api");
    // 调用API
    callAPIWithFile(API.forecast, formData,
        (response) => {
            clearTimeout(timeout);
            hideLoading();
            try {
                updateForecastDisplay(response);
                showRangeControls();
            } catch (e) {
                handleError('处理预测结果时出错: ' + e.message);
            }
        },
        (error) => {
            clearTimeout(timeout);
            hideLoading();
            handleError('预测失败: ' + (error.message || '服务器错误'));
        }
    );
}

function updateForecastDisplay(response) {
    try {
        // 验证响应数据
        if (!response?.data) {
            throw new Error('无效的API响应');
        }

        const data = response.data;

        // 严格数据验证
        if (!validateChartData(data)) {
            throw new Error('数据格式不正确');
        }

        // 保存完整数据
        allTimestamps = data.timestamps;
        allChartData = {
            originData: data.originData || [],
            predictData: data.predictData || [],
            seasonalData: data.seasonalData || [],
            trendData: data.trendData || [],
            residualData: data.residualData || []
        };

        // 更新图表显示
        updateCharts(0, allTimestamps.length - 1);

        // 初始化范围选择器
        initRangeSelector();

    } catch (error) {
        console.error('更新图表失败:', error);
        handleError('图表渲染失败: ' + error.message);
    }
}

function initRangeSelector() {
    // 确保数据已加载
    if (!allTimestamps || allTimestamps.length === 0) {
        console.error('无法初始化滑块：无时间戳数据');
        return;
    }
    const sliderElement = document.getElementById('range-slider');
    if (!sliderElement) {
        console.error('找不到滑块容器元素');
        return;
    }

    sliderElement.innerHTML = '';
    sliderElement.style.display = 'block';
    // 销毁现有滑块
    if (rangeSlider) {
        rangeSlider.destroy();
    }

    // 创建新滑块
    try {
        // 初始化滑块（添加存在性检查）
        if (typeof noUiSlider === 'undefined') {
            throw new Error('noUiSlider 库未正确加载');
        }

        const maxIndex = Math.max(allTimestamps.length - 1, 0);

        rangeSlider = noUiSlider.create(sliderElement, {
            start: [0, maxIndex],
            connect: true,
            range: {
                min: 0,
                max: Math.max(maxIndex, 1) // 防止长度为0时出错
            },
            step: 1,
            // tooltips: [true, true],
            behaviour: 'drag-tap',
            format: {
                to: value => {
                    const idx = clampIndex(Math.round(value));
                    return allTimestamps[idx] || '';
                },
                from: value => {
                    const idx = allTimestamps.indexOf(value);
                    return clampIndex(idx !== -1 ? idx : 0);
                }
            }
        });

        const safeHandler = (handler) => (values) => {
            try {
                const startIdx = clampIndex(Math.round(values[0]));
                const endIdx = clampIndex(Math.round(values[1]));
                if (!validateIndexes(startIdx, endIdx)) return;
                handler(startIdx, endIdx);
            } catch (error) {
                console.error('滑块事件处理失败:', error);
            }
        };
        rangeSlider.on('slide', safeHandler((s, e) => updatePreviewRange(s, e)));
        rangeSlider.off('change'); // 先移除旧监听
        rangeSlider.on('change', (values) => {
            console.log('滑块变化值:', values); // 调试日志
            const [start, end] = values.map(date => {
                const index = allTimestamps.indexOf(date);
                return clampIndex(index !== -1 ? index : 0);
            });
            console.log("start=" + start, "end=" + end);
            console.log("currentStart=" + currentStart, "currentEnd=" + currentEnd);
            if (start === currentStart && end === currentEnd) {
                console.log('忽略未变化的范围');
                return;
            }
            currentStart = start;
            currentEnd = end;
            updateCharts(start, end);
        });
    } catch (error) {
        console.error('Slider初始化失败:', error);
        sliderElement.innerHTML = '<p class="text-red-500">范围控件初始化失败</p>';
    }
}


// ========== 辅助函数 ==========

// 辅助函数：创建系列配置

function validateIndexes(startIdx, endIdx) {
    const isValid = (
        Number.isInteger(startIdx) &&
        Number.isInteger(endIdx) &&
        startIdx >= 0 &&
        endIdx < allTimestamps.length &&
        startIdx <= endIdx
    );

    if (!isValid) {
        console.error(`非法索引范围: ${startIdx}-${endIdx}`, {
            length: allTimestamps.length,
            startIdx,
            endIdx
        });
        return false;
    }
    return true;
}

// 辅助函数：限制索引范围
function clampIndex(index) {
    return Math.min(Math.max(Number(index) || 0, 0), allTimestamps.length - 1);
}



function applyDateRange() {
    const startDate = $('#range-start').val();
    const endDate = $('#range-end').val();

    if (!startDate || !endDate) {
        showError('请选择完整的日期范围');
        return;
    }

    const startIdx = allTimestamps.indexOf(startDate);
    const endIdx = allTimestamps.indexOf(endDate);

    if (startIdx === -1 || endIdx === -1) {
        showError('选择的日期不在数据范围内');
        return;
    }

    if (startIdx > endIdx) {
        showError('开始日期不能晚于结束日期');
        return;
    }

    rangeSlider.set([startIdx, endIdx]);
    updateCharts(startIdx, endIdx);
}

function resetChartRange() {
    rangeSlider.set([0, allTimestamps.length - 1]);
    updateCharts(0, allTimestamps.length - 1);
    $('#range-start').val('');
    $('#range-end').val('');
}

function updatePreviewRange(startIdx, endIdx) {
    $('#range-start').val(allTimestamps[startIdx]);
    $('#range-end').val(allTimestamps[endIdx]);
}

function showLoading() {
    const loadingIndicator = document.getElementById('loading-indicator');
    if (loadingIndicator) {
        loadingIndicator.style.display = 'flex'; // 确保元素显示
    }
}

function hideLoading() {
    const loadingIndicator = document.getElementById('loading-indicator');
    if (loadingIndicator) {
        loadingIndicator.style.display = 'none'; // 确保元素隐藏
    }
}


function showError(message) {
    const errorElement = document.getElementById('error-message');
    errorElement.textContent = message;
    errorElement.classList.remove('hidden');
}

function hideError() {
    document.getElementById('error-message').classList.add('hidden');
}

function resetUIState() {
    hideError();
    hideRangeControls();
}

function showRangeControls() {
    document.getElementById('range-controls').classList.remove('hidden');
}

function hideRangeControls() {
    document.getElementById('range-controls').classList.add('hidden');
}

function handleError(message) {
    hideLoading();
    showError(message);
    hideRangeControls();
}